package com.xinke.module.system.manager.auth;

import cn.hutool.core.util.ObjectUtil;
import com.xinke.component.common.enums.UserTypeEnum;
import com.xinke.component.common.util.monitor.TracerUtils;
import com.xinke.component.common.util.servlet.ServletUtils;
import com.xinke.module.system.api.logger.dto.LoginLogCreateReqDTO;
import com.xinke.module.system.enums.logger.LoginResultEnum;
import com.xinke.module.system.model.entity.oauth2.OAuth2AccessTokenDO;
import com.xinke.module.system.model.entity.user.AdminUserDO;
import com.xinke.module.system.service.logger.LoginLogService;
import com.xinke.module.system.service.member.MemberService;
import com.xinke.module.system.service.oauth2.OAuth2AccessTokenService;
import com.xinke.module.system.service.user.AdminUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author yzx
 * @CreateTime 2025/3/30 19:38
 * @Version 1.0
 * @Description:
 */
@Component
public class AuthManager {
    @Resource
    private OAuth2AccessTokenService oauth2TokenService;
    @Resource
    private LoginLogService loginLogService;

    @Resource
    private AdminUserService userService;
    @Resource
    private MemberService memberService;

    public void logout(String token, Integer logType) {
        // 删除访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenDO.getUserId(), accessTokenDO.getUserType(), logType);
    }

    private void createLogoutLog(Long userId, Integer userType, Integer logType) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType);
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(userType);
        if (ObjectUtil.equal(getUserType().getValue(), userType)) {
            reqDTO.setUserName(getUsername(userId));
        } else {
            reqDTO.setUserName(memberService.getMemberUserMobile(userId));
        }
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(ServletUtils.getClientIP());
        reqDTO.setLoginResult(LoginResultEnum.SUCCESS.getResult());
        loginLogService.createLoginLog(reqDTO);
    }

    private String getUsername(Long userId) {
        if (userId == null) {
            return null;
        }
        AdminUserDO user = userService.getAdminUser(userId);
        return user != null ? user.getUserName() : null;
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.ADMIN;
    }
}
